package com.hornsun.jwt;

import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author cwc
 * @date 2017/4/24 0024
 */
public class AuthorizedClient implements UserDetails, CredentialsContainer {
    public static final String CREDENTIAL_WITH_JWT_TOEKN = "credential.with.jwt.token";
    private static final String VIP = "VIP";
    private String id;
    private String username;
    private String password;
    private Set<GrantedAuthority> authorities;

    public AuthorizedClient(String id, String username, String password, String roleName, String typeName) {
        this.username = username;
        this.password = password;
        this.id = id;
        authorities = new HashSet<>();
        authorities.add(new SimpleGrantedAuthority(roleName));
        if (VIP.equalsIgnoreCase(typeName)) {
            authorities.add(new SimpleGrantedAuthority(typeName));
        }
    }

    public AuthorizedClient(String id, String username, String password, List<?> authorities) {
        this.username = username;
        this.password = password;
        this.id = id;
        this.authorities = new HashSet<>();
        for (Object authority : authorities) {
            this.authorities.add(new SimpleGrantedAuthority((String) authority));
        }

    }

    public boolean isVip() {
        return authorities.contains(new SimpleGrantedAuthority(VIP));
    }

    public String getId() {
        return id;
    }

    public void downGradeToNormal() {
        authorities.remove(new SimpleGrantedAuthority(VIP));
    }

    public void upgradeToVIP() {
        authorities.add(new SimpleGrantedAuthority(VIP));
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public void eraseCredentials() {
        this.password = null;
    }

}
